package service.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import db.MyHibernateSessionFactory;
import entity.Contest;
import entity.Follow;
import service.FollowDAO;

public class FollowDAOImpl implements FollowDAO{

	

	@Override
	public List<Contest> query(int account_id) {
		Transaction tx = null;
		Session session = MyHibernateSessionFactory.getSessionFactory().getCurrentSession();
		List<Contest> conlist = null;
		try {
			tx = session.beginTransaction();
			String hql = "select C FROM Contest C, Follow F "
					+ "WHERE C.contestId = F.id.contest.contestId and F.id.account.accountId=?"
					+ "ORDER BY C.contestStartTime DESC";
			System.out.println("tuxue3" + account_id);
			Query query = session.createQuery(hql);
			System.out.println("tuxue4");
			query.setParameter(0, account_id);
			
			conlist = query.list();
			System.out.println("conlist_size=" + conlist.size());
			for (int i = 0; i < conlist.size(); i++) {
				System.out.println(conlist.get(i).toString());
				
			}
			tx.commit();
			return  conlist;
		} catch (Exception e) {
			// TODO: handle exception
			if(tx != null) tx.rollback();
			e.printStackTrace();
			System.out.println("tuxue5");
			return null;
		}
		finally{
			System.out.println("tuxue5");
			tx=null;
		}
		
	}

	@Override
	public boolean signUp(Follow fo) {
		Transaction tx = null;
		Session session = MyHibernateSessionFactory.getSessionFactory().getCurrentSession();
		try {
			tx = session.beginTransaction();
			
			session.save(fo);
			
			tx.commit();
			return  true;
		} catch (Exception e) {
			// TODO: handle exception
			if(tx != null) tx.rollback();
			e.printStackTrace();
			return false;
		}
		finally{
			tx=null;
		}
	}

	
}
